<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="供应商名" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:supplier:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:supplier:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:supplier:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:supplier:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="supplierList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="100"/>
      <el-table-column label="供应商名" align="center" prop="supplierName"/>
      <el-table-column label="法人" align="center" prop="legalPerson"/>
      <el-table-column label="营业执照" align="center" prop="businessLicense">
        <template slot-scope="scope">
          <image-preview :src="scope.row.businessLicense" :image-width="100" :image-height="100"/>
        </template>
      </el-table-column>
      <el-table-column label="产品" prop="proName" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleShowProduct(scope.row)"
          >查看供应商产品
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="地图位置" align="center">
        <template slot-scope="scope">
    <span @click="showMap(scope.row.longitude , scope.row.latitude)">
      <el-button
        type="primary"
        plain
        size="mini"
      >查看地图</el-button>
    </span>
        </template>
      </el-table-column>
      <el-table-column label="供应商规模" align="center" prop="scale"/>
      <el-table-column label="操作" align="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:supplier:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:supplier:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看地图显示 -->
    <el-dialog
      title="地图显示"
      :visible.sync="mapDialogVisible"
      width="70%"
      append-to-body
    >
      <div id="map" style="height: 400px;"></div>
    </el-dialog>

    <!-- 添加或修改供应商位置信息对话框 -->
    <el-dialog
      title="地图显示"
      :visible.sync="newMapDialogVisible"
      width="70%"
      append-to-body
    >
      <div id="map" style="height: 400px;"></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmLocation">确定</el-button>
        <el-button @click="newMapDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改供应商信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="供应商名" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请输入供应商名"/>
        </el-form-item>
        <el-form-item label="法人" prop="legalPerson">
          <el-input v-model="form.legalPerson" placeholder="请输入法人"/>
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense">
          <ImageUpload v-model="form.businessLicense" :limit="1" />
        </el-form-item>
        <el-form-item label="经营规模" prop="scale">
          <el-select v-model="form.scale" placeholder="请选择规模">
            <el-option
              v-for="dict in scaleOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="openMapDialog">在地图中选择位置
          </el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看营业执照 -->
    <el-dialog
      title="查看营业执照"
      :visible.sync="agreementDialogVisible"
      width="50%"
      append-to-body
    >
      <img :src="currentLicenseImage" alt="营业执照" style="width: 100%; height: auto;"/>
    </el-dialog>

    <!--查看供应商可以生产的产品对话框-->
    <el-dialog :title="title" :visible.sync="proShow" width="500px" append-to-body>
      <el-form :model="form.productList" label-width="100px">
        <el-form-item label="产品名称">
          <el-tree
            class="tree-border"
            :data="productList"
            :default-expand-all="isExpandAll"
            node-key="proId"
            ref="product"
            empty-text="无数据"
            :props="{label: 'proName', children: 'children'}"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSupplier,
  getSupplier,
  delSupplier,
  addSupplier,
  updateSupplier,
  WatchProduct
} from "@/api/system/supplier";
import {listProduct} from "@/api/system/product";
import AMapLoader from '@amap/amap-jsapi-loader';
//树形下拉框组件
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import Treeselect from "@riophae/vue-treeselect";

export default {
  name: "Supplier",
  components: { Treeselect },
  data() {
    return {
      // 是否展开
      isExpandAll: true,
      // 刷新表格
      refreshTable: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 弹出层标题
      mapDialogVisible: false,
      newMapDialogVisible: false,
      agreementDialogVisible: false,
      //当前营业执照
      currentLicenseImage: '',
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商信息表格数据
      supplierList: [],
      // 产品分类（二级）表格数据
      productList: [],
      // 供应商规模字典
      scaleOptions: [
        {label: "大型供应商", value: "大型供应商"},
        {label: "中型供应商", value: "中型供应商"},
        {label: "小型供应商", value: "小型供应商"},
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      proShow: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierId: null,
        supplierName: null,
        legalPerson: null,
        scale: null,
        businessLicense: null,
        longitude: null,
        latitude: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        supplierName: [
          {required: true, message: "供应商名不能为空", trigger: "blur"}
        ],
        legalPerson: [
          {required: true, message: "法人不能为空", trigger: "blur"}
        ],
        scale: [
          {required: true, message: "经营规模不能为空", trigger: "change"}
        ],
        businessLicense: [
          {required: true, message: "营业执照不能为空", trigger: "change"}
        ],
      },
      map: null,
      marker: null,
      mapLocation: {longitude: null, latitude: null},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询供应商信息列表 */
    getList() {
      this.loading = true;
      listSupplier(this.queryParams).then(response => {
        // 过滤 parentId 等于 0 或 null 的数据
        this.supplierList = response.rows;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.proShow = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        supplierId: null,
        supplierName: null,
        productionStatus: null,
        longitude: null,
        latitude: null,
        supplierGrade: null,
        supplierSize: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.supplierId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row !== undefined) {
        this.form.parentId = row.supplierId;
      }
      this.open = true;
      this.title = "添加供应商";
      listSupplier().then(response => {
        this.supplierList = this.handleTree(response.data, "supplierId");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const supplierId = row.supplierId || this.ids
      getSupplier(supplierId).then(response => {
        this.form = response.data;
        // this.productList = this.form.productIds;
        this.open = true;
        this.title = "修改供应商信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.supplierId !== null) {
            updateSupplier(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSupplier(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const supplierIds = row.supplierId || this.ids;
      this.$modal.confirm('是否确认删除供应商信息编号为"' + supplierIds + '"的数据项？').then(function () {
        return delSupplier(supplierIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/supplier/export', {
        ...this.queryParams
      }, `supplier_${new Date().getTime()}.xlsx`)
    },
    handleCheckChange(checkedNodes) {

    },
    openMapDialog() {
      this.newMapDialogVisible = true;
      AMapLoader.load({
        key: '77b44b6f84ac46b347e84a0ee471f45f',
        version: '1.4.15',
        plugins: ['AMap.Geocoder']
      }).then(AMap => {
        const center = this.form.longitude && this.form.latitude
          ? [this.form.longitude, this.form.latitude]
          : [111.56, 40.79];

        this.map = new AMap.Map('map', {
          center,
          zoom: 15
        });

        if (this.form.longitude && this.form.latitude) {
          this.marker = new AMap.Marker({
            position: center,
            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
            map: this.map
          });
        }

        this.map.on('click', (e) => {
          const {lng, lat} = e.lnglat;
          this.mapLocation = {longitude: lng, latitude: lat};

          if (this.marker) {
            this.marker.setPosition([lng, lat]);
          } else {
            this.marker = new AMap.Marker({
              position: [lng, lat],
              icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
              map: this.map
            });
          }
        });
      }).catch(e => {
        console.error("高德地图初始化失败：", e);
      });
    },

    showMap(longitude, latitude) {
      this.mapLocation = {longitude, latitude};
      this.mapDialogVisible = true;
      AMapLoader.load({
        key: '77b44b6f84ac46b347e84a0ee471f45f',
        version: '1.4.15',
        plugins: ['AMap.Geocoder']
      }).then(AMap => {
        const center = longitude && latitude
          ? [longitude, latitude]
          : [111.56, 40.79];

        this.map = new AMap.Map('map', {
          center,
          zoom: 15
        });

        this.marker = new AMap.Marker({
          position: center,
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          map: this.map
        });
      }).catch(e => {
        console.error("高德地图初始化失败：", e);
      });
    },

    confirmLocation() {
      this.form.longitude = this.mapLocation.longitude;
      this.form.latitude = this.mapLocation.latitude;
      this.newMapDialogVisible = false;
    },
    handleShowProduct(row){
      this.reset();
      const supplierId = row.supplierId || this.ids;
      WatchProduct(supplierId).then(response => {
        this.productList = this.handleTree(response.data, "proId", "proParentId");
        this.form = response.data;
        this.proShow = true;
        this.title = "查看生产产品";
      });
      console.log(this.productList);
    },
  }
};
</script>
